from flask import Blueprint, request, jsonify
from src.services.metaso_service import MetasoService
from src.models.database import db
import traceback

# 创建蓝图
metaso_bp = Blueprint('metaso', __name__, url_prefix='/api/metaso')

# 初始化服务
metaso_service = MetasoService()


@metaso_bp.route('/query', methods=['POST'])
def start_query():
    """启动Metaso查询任务"""
    try:
        data = request.get_json()
        
        if not data or 'query_text' not in data:
            return jsonify({
                'success': False,
                'message': '缺少查询文本参数'
            }), 400
        
        query_text = data['query_text']
        scope = data.get('scope', 'webpage')
        size = data.get('size', 20)
        
        # 启动查询任务
        task_id = metaso_service.start_query_task(query_text, scope, size)
        
        return jsonify({
            'success': True,
            'message': '查询任务已启动',
            'task_id': task_id
        })
        
    except Exception as e:
        print(f"启动查询任务失败: {str(e)}")
        traceback.print_exc()
        return jsonify({
            'success': False,
            'message': f'启动查询任务失败: {str(e)}'
        }), 500


@metaso_bp.route('/task/<task_id>/status', methods=['GET'])
def get_task_status(task_id):
    """获取查询任务状态"""
    try:
        status = metaso_service.get_query_task_status(task_id)
        return jsonify({
            'success': True,
            'data': status
        })
        
    except Exception as e:
        print(f"获取任务状态失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'获取任务状态失败: {str(e)}'
        }), 500


@metaso_bp.route('/query/<query_id>', methods=['GET'])
def get_query_data(query_id):
    """获取查询数据"""
    try:
        query_data = metaso_service.get_query_data(query_id)
        
        if not query_data:
            return jsonify({
                'success': False,
                'message': '查询数据不存在'
            }), 404
        
        return jsonify({
            'success': True,
            'data': query_data
        })
        
    except Exception as e:
        print(f"获取查询数据失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'获取查询数据失败: {str(e)}'
        }), 500


@metaso_bp.route('/queries', methods=['GET'])
def get_all_queries():
    """获取所有查询记录"""
    try:
        limit = request.args.get('limit', 50, type=int)
        queries = metaso_service.get_all_queries(limit)
        
        return jsonify({
            'success': True,
            'data': queries
        })
        
    except Exception as e:
        print(f"获取查询记录失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'获取查询记录失败: {str(e)}'
        }), 500


@metaso_bp.route('/search', methods=['POST'])
def search_by_keywords():
    """根据关键词搜索历史查询"""
    try:
        data = request.get_json()
        
        if not data or 'keywords' not in data:
            return jsonify({
                'success': False,
                'message': '缺少关键词参数'
            }), 400
        
        keywords = data['keywords']
        limit = data.get('limit', 20)
        
        if not isinstance(keywords, list):
            return jsonify({
                'success': False,
                'message': '关键词必须是数组格式'
            }), 400
        
        results = metaso_service.search_by_keywords(keywords, limit)
        
        return jsonify({
            'success': True,
            'data': results
        })
        
    except Exception as e:
        print(f"关键词搜索失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'关键词搜索失败: {str(e)}'
        }), 500


@metaso_bp.route('/statistics', methods=['GET'])
def get_statistics():
    """获取查询统计信息"""
    try:
        stats = metaso_service.get_statistics()
        
        return jsonify({
            'success': True,
            'data': stats
        })
        
    except Exception as e:
        print(f"获取统计信息失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'获取统计信息失败: {str(e)}'
        }), 500


@metaso_bp.route('/task/<task_id>/cancel', methods=['POST'])
def cancel_task(task_id):
    """取消查询任务"""
    try:
        success = metaso_service.cancel_query_task(task_id)
        
        if success:
            return jsonify({
                'success': True,
                'message': '任务已取消'
            })
        else:
            return jsonify({
                'success': False,
                'message': '任务不存在或无法取消'
            }), 404
        
    except Exception as e:
        print(f"取消任务失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'取消任务失败: {str(e)}'
        }), 500


@metaso_bp.route('/health', methods=['GET'])
def health_check():
    """健康检查"""
    return jsonify({
        'success': True,
        'message': 'Metaso服务运行正常',
        'timestamp': metaso_service.get_statistics().get('total_queries', 0)
    })
